package com.iagent.plugins;

import com.iagent.request.HttpExecutor;
import com.iagent.util.ClassUtils;
import com.iagent.util.CollectionUtils;

import java.lang.reflect.Proxy;
import java.util.List;

/**
 * Plugin processor
 *
 * @author liujieyu
 * @since 2.1.0
 * @see InterceptorInvocation
 */
public class PluginChain {

    /**
     * Create proxy objects using the JDK dynamic proxy
     *
     * @param target real object
     * @return proxy object
     * @since 2.1.0
     */
    private Object newProxyInstance(Object target, Interceptor interceptor) {
        return Proxy.newProxyInstance(ClassUtils.getClassLoader(), new Class[]{HttpExecutor.class}, new InterceptorInvocation(target, interceptor));
    }

    /**
     * Load all interceptors and generate interceptor links
     *
     * @param interceptors
     * @param target
     * @return
     */
    public Object loadAllPlugins(List<Interceptor> interceptors, Object target) {
        if (CollectionUtils.isNotEmpty(interceptors)) {
            // The proxy object is generated and the link is generated
            for (Interceptor interceptor : interceptors) {
                target = this.newProxyInstance(target, interceptor);
            }
        }
        return target;
    }
}
